/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.wsrm.impl;

import javax.xml.namespace.QName;

import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;

import cgl.narada.wsinfra.exception.WsFaultException;
import cgl.narada.wsinfra.schemas.soap.BodyType;
import cgl.narada.wsinfra.schemas.soap.EnvelopeDocument;
import cgl.narada.wsinfra.schemas.soap.EnvelopeType;
import cgl.narada.wsinfra.schemas.soap.HeaderType;
import cgl.narada.wsinfra.schemas.utility.AttributedURI;
import cgl.narada.wsinfra.schemas.utility.IdentifierDocument;
import cgl.narada.wsinfra.schemas.wsrm.AckRequestedDocument;
import cgl.narada.wsinfra.schemas.wsrm.CreateSequenceDocument;
import cgl.narada.wsinfra.schemas.wsrm.CreateSequenceResponseDocument;
import cgl.narada.wsinfra.schemas.wsrm.HandshakeType;
import cgl.narada.wsinfra.schemas.wsrm.SequenceAcknowledgementDocument;
import cgl.narada.wsinfra.schemas.wsrm.SequenceDocument;
import cgl.narada.wsinfra.schemas.wsrm.TerminateSequenceDocument;
import cgl.narada.wsinfra.util.QNameLocator;
import cgl.narada.wsinfra.wsrm.WsrmFaults;
import cgl.narada.wsinfra.wsrm.WsrmNodeUtils;
import cgl.narada.wsinfra.wsrm.WsrmProcessingFactory;
import cgl.narada.wsinfra.wsrm.WsrmQNames;
/** 
    This is a utility class which faciliates the retrieval of elements 
    pertaining to WSRM that reside in the SOAP enevelope.
    
    @author Shrideep Pallickara
    $Date: 2005/07/29 22:41:30 $
    $Revision: 1.3 $
*/


public class WsrmNodeUtilsImpl implements WsrmNodeUtils  {
  private static final WsrmNodeUtils instance = new WsrmNodeUtilsImpl();

  private QNameLocator qNameLocator;
  private WsrmFaults wsrmFaults;
  private WsrmQNames wsrmQNames;
  private String moduleName = "WsrmNodeUtils: ";


  private WsrmNodeUtilsImpl() {
    wsrmFaults = WsrmProcessingFactory.getWsrmFaults();
    wsrmQNames = WsrmQNames.getInstance();

    qNameLocator = QNameLocator.getInstance();
  }


  public static WsrmNodeUtils getInstance() {
    return instance;
  }

  /** Retrieves element from the body of the SOAP message */
  public CreateSequenceDocument 
  getCreateSequenceDocument(EnvelopeDocument envelopeDocument)
    throws WsFaultException {
    BodyType bodyType = getEnvelopeBody(envelopeDocument);

    XmlCursor bodyCursor = bodyType.newCursor();
    QName createSequenceQName = wsrmQNames.getCreateSequence();
    checkForElement(bodyCursor, createSequenceQName);

    boolean creationProblems = false;
    CreateSequenceDocument createSequenceDocument = null;

    String faultReason="Problems parsing createSequence element";
    try {
      createSequenceDocument =
	CreateSequenceDocument.Factory.parse( bodyCursor.xmlText() );
    } catch (XmlException xmlEx) {
      creationProblems = true;
      faultReason += xmlEx.toString();
    }

    bodyCursor.dispose();
   
    if (createSequenceDocument == null || creationProblems) {
      throwInvalidMessageFault(faultReason);
    }

    return createSequenceDocument;
  }
  
  
  /** Retrieves element from the body of the SOAP message. */
  public CreateSequenceResponseDocument 
  getCreateSequenceResponseDocument(EnvelopeDocument envelopeDocument)
    throws WsFaultException {
    BodyType bodyType = getEnvelopeBody(envelopeDocument);

    XmlCursor bodyCursor = bodyType.newCursor();
    QName createSequenceResponseQName =wsrmQNames.getCreateSequenceResponse();
    checkForElement(bodyCursor, createSequenceResponseQName);

    boolean creationProblems = false;
    CreateSequenceResponseDocument createSequenceResponseDocument = null;

    String faultReason="Problems parsing createSequenceResponse element";
    try {
      createSequenceResponseDocument =
	CreateSequenceResponseDocument.Factory.parse( bodyCursor.xmlText() );
    } catch (XmlException xmlEx) {
      creationProblems = true;
      faultReason += xmlEx.toString();
    }

    bodyCursor.dispose();
   
    if (createSequenceResponseDocument == null || creationProblems) {
      throwInvalidMessageFault(faultReason);
    }

    HandshakeType createSequenceResponse = 
       createSequenceResponseDocument.getCreateSequenceResponse();
    if (createSequenceResponse == null) {
      throwInvalidMessageFault(faultReason);
    }
    
    AttributedURI identifierUri = createSequenceResponse.getIdentifier();
    if (identifierUri == null) {
      throwInvalidMessageFault(faultReason + 
			       "The identifier element is NULL!");
    } 

    return createSequenceResponseDocument;
  }
  
  
  /** Retrieves element from the body of the SOAP message. */
  public TerminateSequenceDocument
  getTerminateSequenceDocument(EnvelopeDocument envelopeDocument)
    throws WsFaultException {
    BodyType bodyType = getEnvelopeBody(envelopeDocument);

    XmlCursor bodyCursor = bodyType.newCursor();
    QName terminateSequenceQName = wsrmQNames.getTerminateSequence();
    checkForElement(bodyCursor, terminateSequenceQName);

    boolean creationProblems = false;
    TerminateSequenceDocument terminateSequenceDocument = null;

    String faultReason="Problems parsing terminateSequence element";
    try {
      terminateSequenceDocument =
	TerminateSequenceDocument.Factory.parse( bodyCursor.xmlText() );
    } catch (XmlException xmlEx) {
      creationProblems = true;
      faultReason += xmlEx.toString();
    }

    bodyCursor.dispose();
   
    if (terminateSequenceDocument == null || creationProblems) {
      throwInvalidMessageFault(faultReason);
    }

    return terminateSequenceDocument;
  }

  
  /** Retrieves the IdentifierDocument from within the speicified XmlCursor */
  public IdentifierDocument
  getIdentifierDocument(XmlCursor xmlCursor) throws WsFaultException {
    QName identifierQName = wsrmQNames.getIdentifier();
    checkForElement(xmlCursor, identifierQName);
    
    boolean creationProblems = false;
    IdentifierDocument identifierDocument = null;

    String faultReason="Problems parsing identifier element";
    try {
      identifierDocument =
	IdentifierDocument.Factory.parse( xmlCursor.xmlText() );
    } catch (XmlException xmlEx) {
      creationProblems = true;
      faultReason += xmlEx.toString();
    }

    if (identifierDocument == null || creationProblems) {
      throwInvalidMessageFault(faultReason);
    }

    return identifierDocument;
  }
  

  /** Retrieves the Sequence Acknowledgement document from within the
      specified XmlCursor */
  public SequenceAcknowledgementDocument
  getSequenceAcknowledgement(EnvelopeDocument envelopeDocument) 
    throws WsFaultException {

    HeaderType headerType = getEnvelopeHeader(envelopeDocument);

    XmlCursor headerCursor = headerType.newCursor();
    QName sequenceAcknowledgementQName = 
      wsrmQNames.getSequenceAcknowledgement();
    checkForElement(headerCursor, sequenceAcknowledgementQName);

    boolean creationProblems = false;
    SequenceAcknowledgementDocument sequenceAcknowledgementDocument = null;

    String faultReason ="Problems parsing SequenceAcknowledgement element.\n";

    try {
      sequenceAcknowledgementDocument =
	SequenceAcknowledgementDocument.Factory.parse(headerCursor.xmlText());
    } catch (XmlException xmlEx) {
      creationProblems = true;
      faultReason += xmlEx.toString();
    }

    headerCursor.dispose();
    
    if (sequenceAcknowledgementDocument == null || creationProblems) {
      throwInvalidMessageFault(faultReason);
    }

    return sequenceAcknowledgementDocument;
  }


  /** Retrieves the AckRequested document from within the specified XmlCursor 
   */
  public AckRequestedDocument
  getAckRequested(EnvelopeDocument envelopeDocument) throws WsFaultException {
    
    HeaderType headerType = getEnvelopeHeader(envelopeDocument);

    XmlCursor headerCursor = headerType.newCursor();
    QName ackRequestedQName = wsrmQNames.getAckRequested();
    checkForElement(headerCursor, ackRequestedQName);

    boolean creationProblems = false;
    AckRequestedDocument ackRequestedDocument = null;

    String faultReason ="Problems parsing AckRequested element.\n";

    try {
      ackRequestedDocument =
	AckRequestedDocument.Factory.parse(headerCursor.xmlText());
    } catch (XmlException xmlEx) {
      creationProblems = true;
      faultReason += xmlEx.toString();
    }

    headerCursor.dispose();
    
    if (ackRequestedDocument == null || creationProblems) {
      throwInvalidMessageFault(faultReason);
    }

    return ackRequestedDocument;
  }

  
  /** Retrieves the SequenceDocument from within the specified XmlCursor */
  public SequenceDocument
  getSequenceDocument(EnvelopeDocument envelopeDocument) 
    throws WsFaultException {
    HeaderType headerType = getEnvelopeHeader(envelopeDocument);

    XmlCursor headerCursor = headerType.newCursor();
    QName sequenceQName = wsrmQNames.getSequence();
    checkForElement(headerCursor, sequenceQName);

    boolean creationProblems = false;
    SequenceDocument sequenceDocument = null;

    String faultReason ="Problems parsing Sequence element.\n";

    try {
      sequenceDocument =
	SequenceDocument.Factory.parse(headerCursor.xmlText());
    } catch (XmlException xmlEx) {
      creationProblems = true;
      faultReason += xmlEx.toString();
    }

    headerCursor.dispose();
    
    if (sequenceDocument == null || creationProblems) {
      throwInvalidMessageFault(faultReason);
    }

    return sequenceDocument;
  }


   /** Check to see if the element exists and position the cursor at the
      right location if it does */
  private void checkForElement(XmlCursor xmlCursor, QName qName)
    throws WsFaultException {

    String faultReason = "";
    boolean foundQName = qNameLocator.locateQName(xmlCursor, qName);

    if (!foundQName) {
      xmlCursor.dispose();
      faultReason = "Unable to Locate element [" + qName +
	"], no further processing possible.";
      throwInvalidMessageFault(faultReason);
    }
  }


   /** Checks for problems with the envelope and returns the envelope body */
  private BodyType getEnvelopeBody(EnvelopeDocument envelopeDocument)
    throws WsFaultException {
    String faultReason = "";
    if (envelopeDocument == null) {
      faultReason = "The specified envelope is NULL";
      throwInvalidMessageFault(faultReason);
    }

    BodyType bodyType = envelopeDocument.getEnvelope().getBody();

    if (bodyType == null) {
      faultReason = "The body of SOAP message is NULL!";
      throwInvalidMessageFault(faultReason);
    }

    return bodyType;
  }



   /** Checks for problems with the envelope and returns the envelope body */
  private HeaderType getEnvelopeHeader(EnvelopeDocument envelopeDocument)
    throws WsFaultException {
    String faultReason = "";
    if (envelopeDocument == null) {
      faultReason = "The specified envelope is NULL";
      throwInvalidMessageFault(faultReason);
    }

    EnvelopeType envelope = envelopeDocument.getEnvelope();
    if (!envelope.isSetHeader()) {
      faultReason = "This SOAP message DOES NOT have a header!";
    }

    HeaderType headerType = envelope.getHeader();

    if (headerType == null) {
      faultReason = "The header of the SOAP message is NULL!";
      throwInvalidMessageFault(faultReason);
    }

    return headerType;
  }



  /** Throw a WsFaultException, initialized with the invalid message QName
      and the specified reason */
  private void throwInvalidMessageFault(String reason)
    throws WsFaultException {

    WsFaultException wsFaultException = 
      new WsFaultException(wsrmFaults.getSoapSenderQName(), reason);
    
    wsFaultException.setAddSoapHeaderElement(wsrmFaults.getInvalidMessage());

    throw wsFaultException;
  }
  
}




